package org.wheel.plugins.starter.autoconfigure;

import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;
import jakarta.annotation.PostConstruct;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Primary;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import org.wheel.plugins.toolkit.jdbc.pool.util.DynamicJdbcPoolUtil;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@AutoConfigureAfter(DataSourceAutoConfiguration.class)
@ConditionalOnMissingBean(DataSource.class) // 此时官方池已创建完，判断正确
//@EnableConfigurationProperties(DynamicDataSourceProperties.class) // ← 同样
public class DynamicDataSourceAutoConfiguration {

    private final DynamicDataSourceProperties properties;

    public DynamicDataSourceAutoConfiguration(DynamicDataSourceProperties properties) {
        this.properties = properties;
    }

    /**
     * 启动即预热：主数据源 + 全部多数据源一次性建池
     */
    @PostConstruct
    public void warmUp() {
        log.info("[DynamicDataSourceAutoConfiguration] 启动即预热：主数据源 + 全部多数据源一次性建池");
//        DynamicJdbcPoolUtil util = DynamicJdbcPoolUtil.getInstance();
        // 主数据源
        if (StrUtil.isNotBlank(properties.getUrl())) {
            String name = StrUtil.blankToDefault(properties.getName(), properties.getDefaultName());
            properties.setName(name);
//            util.getOrCreateJdbcTemplate(properties);
        }
        // 多数据源
        if (MapUtil.isNotEmpty(properties.getMultiDatasource())) {
            properties.getMultiDatasource().forEach((k, conn) -> {
                if (StrUtil.isBlank(conn.getName())) conn.setName(k);
//                util.getOrCreateJdbcTemplate(conn);
            });
        }
    }

    @Bean
    @Primary // 此时我是主事务管理器
    public PlatformTransactionManager primaryTransactionManager(DynamicJdbcPoolUtil util) {
        DataSource dataSource = util.getOrCreateJdbcTemplate(properties).getDataSource();
        return new DataSourceTransactionManager(dataSource);
    }

    @Bean
    public Map<String, PlatformTransactionManager> multiTransactionManagers(DynamicJdbcPoolUtil util) {
        Map<String, PlatformTransactionManager> map = new HashMap<>();
        if (MapUtil.isNotEmpty(properties.getMultiDatasource())) {
            properties.getMultiDatasource().forEach((k, conn) -> {
                DataSource ds = util.getOrCreateJdbcTemplate(conn).getDataSource();
                map.put(k + "TransactionManager", new DataSourceTransactionManager(ds));
            });
        }
        return map;
    }

    @Bean
    @ConditionalOnMissingBean(DynamicJdbcPoolUtil.class)
    public DynamicJdbcPoolUtil dynamicJdbcPoolUtil() {
        return DynamicJdbcPoolUtil.getInstance();
    }
}